import React, { Suspense } from 'react'
import routes from './routes'
import { Routes, Route, useLocation, useSearchParams, useParams, useNavigate } from 'react-router-dom'

function Element(props) {
  // 每次路由匹配要渲染的组件，这里可以做一些组件渲染前的事：登录态校验、路由参数传递等
  const { component: Component } = props
  let WithComponent = withRoute(Component)
  return <WithComponent />
}

function createRoute(routes) {
  return <>
    {routes.map((item, index) => {
      let { path, children } = item
      return <Route key={index} path={path} element={<Element {...item} />}>
        {Array.isArray(children) ? createRoute(children) : null}
      </Route>
    })}
  </>
}


export default function RouterView() {
  return <Suspense fallback={<>正在加载中...</>}>
    {/* Routes 内部只接受 Route 组件 或 React.Fragement */}
    <Routes>
      {createRoute(routes)}
    </Routes>
  </Suspense>
}


export function withRoute(Component) {
  return function HOC(props) {
    let navigate = useNavigate(),
      location = useLocation(),
      params = useParams(),
      [usp] = useSearchParams()
    return <Component {...props} location={location} params={params} usp={usp} navigate={navigate} />
  }
}